package com.haitaoit.chengquan.module.home.activity.parts;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.car.activity.OrderSubmitActivity;
import com.haitaoit.chengquan.module.home.model.PartsDetailModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.activity.ShowPictureActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.ImageCycleView;
import com.haitaoit.chengquan.view.Img;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.connect.auth.QQAuth;
import com.tencent.open.wpa.WPA;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PartsDetailActivity extends BaseActivity {
    @ViewInject(R.id.detail_sc)
    ScrollView      detail_sc;
    @ViewInject(R.id.detail_button)
    LinearLayout    detail_button;
    @ViewInject(R.id.detail_webview)
    WebView         detail_webview;
    @ViewInject(R.id.home_topImg)
    ImageCycleView  home_topImg;
    @ViewInject(R.id.part_detail_title)
    TextView        part_detail_title;
    @ViewInject(R.id.part_detail_price)
    TextView        part_detail_price;
    @ViewInject(R.id.sales_volume)
    TextView        sales_volume;
    @ViewInject(R.id.evaluate_count)
    TextView        evaluate_count;
    @ViewInject(R.id.center_img)
    CircleImageView center_img;
    @ViewInject(R.id.eva_name)
    TextView        eva_name;
    @ViewInject(R.id.content)
    TextView        content;
    @ViewInject(R.id.specifications)
    TextView        specifications;
    @ViewInject(R.id.addtime)
    TextView        addtime;
    @ViewInject(R.id.detail_guige)
    TextView        detail_guige;
    @ViewInject(R.id.part_addcoll)
    TextView        part_addcoll;
    @ViewInject(R.id.eva_ll)
    LinearLayout    eva_ll;


    private String           id;
    private PartsDetailModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parts_detail);
        ViewUtils.inject(this);


        DisplayMetrics metrics = getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp1 = home_topImg.getLayoutParams();
        lp1.height = metrics.widthPixels;
        home_topImg.setLayoutParams(lp1);

        id = getIntent().getStringExtra("id");
        httpGetaccessories_goods_model();
        WebSettings seting = detail_webview.getSettings();
        seting.setJavaScriptEnabled(true);
        detail_webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                if (newProgress == 100) {
                    hideProgree();
                } else {

                    showProgrees("");
                }
            }

        });

        if (TextUtils.equals(PreferenceUtils.getPrefString("account_type", ""), "1")) {
            detail_button.setVisibility(View.VISIBLE);
            detail_guige.setVisibility(View.VISIBLE);

        } else {
            detail_button.setVisibility(View.GONE);
            detail_guige.setVisibility(View.GONE);
        }

    }

    @OnClick({R.id.left, R.id.part_detail_rb1, R.id.part_detail_rb2, R.id.detail_share,
            R.id.detail_guige, R.id.check_alleva, R.id.parts_detail_gocar, R.id.parts_detail_gobuy,
            R.id.part_addcoll, R.id.part_QQ,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.part_detail_rb1:
                detail_sc.setVisibility(View.VISIBLE);
                detail_button.setVisibility(View.VISIBLE);
                detail_webview.setVisibility(View.GONE);
                break;
            case R.id.part_detail_rb2:
                detail_sc.setVisibility(View.GONE);
                detail_button.setVisibility(View.GONE);
                detail_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.detail_share:// 分享
                httpGetAppshare();
                break;
            case R.id.check_alleva:// 查看全部评价
                intent.setClass(PartsDetailActivity.this, AllEvaActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
                break;
            case R.id.part_QQ:// qq
                if (model.getQq().equals("")) {
                    ToastUtils.showToast("该卖家没有填写QQ！");
                } else {
                    QQAuth mqqAuth = QQAuth.createInstance("1105935142", this);// 10000000为你申请的APP_ID,mContext是上下文
                    WPA mWPA = new WPA(this, mqqAuth.getQQToken());
                    int ret = mWPA.startWPAConversation(this, model.getQq(), "你好");//客服QQ
                    if (ret != 0) {// 如果ret不为0，就说明调用SDK出现了错误
                        ToastUtils.showToast("抱歉，联系客服出现了错误~. error:" + ret);
                    }
                }
                break;
            case R.id.part_addcoll:// 收藏
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    intent.setClass(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                    httpGetaccessories_goods_collection();
                } else {
                    ToastUtils.showToast("该账号不是需求商！");
                }
                break;
            case R.id.detail_guige:// 规格
                SelectSpec(0);
                break;
            case R.id.parts_detail_gocar:// 加入购物车
                SelectSpec(1);
                break;
            case R.id.parts_detail_gobuy:// 立即购买
                SelectSpec(2);
                break;
        }
        super.onClick(v);
    }

    /**
     * 选规格时 下面显示加入购物车和立即购买
     * 点击屏幕下面的加入购物车和立即购买时 显示确定
     */
    public void SelectSpec(final int type) {
        final Intent intent = new Intent();
        Dialog dlg = DialogUtil.ShowSpecDialog(this, type, model, new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                switch (which) {
                    case R.id.add_car:// 加入购物车
                        if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                            intent.setClass(PartsDetailActivity.this, LoginActivity.class);
                            intent.putExtra("tag", "0");
                            startActivity(intent);
                        } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                            httpGetadd_user_cart(model.getSpecifications().get((Integer) obj[0]).getAccessories_goods_specifications_id(), (String) obj[1]);
                        } else {
                            ToastUtils.showToast("您不是需求商！");
                        }
                        break;
                    case R.id.go_buy:// 立即购买
                        if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                            intent.setClass(PartsDetailActivity.this, LoginActivity.class);
                            intent.putExtra("tag", "0");
                            startActivity(intent);
                        } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                            intent.setClass(PartsDetailActivity.this, OrderSubmitActivity.class);
                            intent.putExtra("type", "now");
                            intent.putExtra("product_id", id);
                            intent.putExtra("specid", model.getSpecifications().get((Integer) obj[0]).getAccessories_goods_specifications_id());
                            intent.putExtra("count", (String) obj[1]);
                            startActivity(intent);
                        } else {
                            ToastUtils.showToast("您不是需求商！");
                        }
                        break;
                    case R.id.add_sure:// 确认 点击 加入购物车 立即购买
                        if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                            intent.setClass(PartsDetailActivity.this, LoginActivity.class);
                            intent.putExtra("tag", "0");
                            startActivity(intent);
                        } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                            if (type == 1) {// 加入购物车
                                httpGetadd_user_cart(model.getSpecifications().get((Integer) obj[0]).getAccessories_goods_specifications_id(), (String) obj[1]);
                            } else if (type == 2) {
                                intent.setClass(PartsDetailActivity.this, OrderSubmitActivity.class);
                                intent.putExtra("type", "now");
                                intent.putExtra("product_id", id);
                                intent.putExtra("specid", model.getSpecifications().get((Integer) obj[0]).getAccessories_goods_specifications_id());
                                intent.putExtra("count", (String) obj[1]);
                                startActivity(intent);
                            }
                        } else {
                            ToastUtils.showToast("您不是需求商！");
                        }
                        break;
                }
                super.deal(which, obj);
            }
        });
        dlg.setCanceledOnTouchOutside(true);
        dlg.show();

        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;// 屏幕宽度（像素）
        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
        params.width = width;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.getWindow().setAttributes(params);
    }

    // 详情
    private void httpGetaccessories_goods_model() {
        String user_id = PreferenceUtils.getPrefString("user_id", "");
        if ("".equals(user_id))
            user_id = "0";
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("user_id", user_id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("user_id", user_id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getaccessories_goods_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, PartsDetailModel.class);
                            home_topImg.setImageResources(model.getImg_list(), listener);
                            part_detail_title.setText(model.getTitle());
                            part_detail_price.setText("¥ " + model.getPrice());
                            sales_volume.setText("月销量：" + model.getSales_volume() + "件");
                            evaluate_count.setText("交易评价（" + model.getEvaluate_count() + "）");
                            detail_webview.loadDataWithBaseURL("aboutblank", model.getContent(), "text/html", "utf-8", null);
                            if (model.getIs_collection().equals("1")) {
                                Drawable img = getResources().getDrawable(R.mipmap.pic37_1);
                                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
                                part_addcoll.setCompoundDrawables(null, img, null, null);
                            } else if (model.getIs_collection().equals("2")) {
                                Drawable img = getResources().getDrawable(R.mipmap.pic37_2);
                                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
                                part_addcoll.setCompoundDrawables(null, img, null, null);
                            }

                            if (model.getEvaluation_model() != null) {
                                ImageLoader.getInstance().displayImage(model.getEvaluation_model().getHead_portrait(), center_img);
                                eva_name.setText(model.getEvaluation_model().getName());
                                content.setText(model.getEvaluation_model().getContent());
                                specifications.setText("规格：" + model.getEvaluation_model().getSpecifications());
                                addtime.setText(model.getEvaluation_model().getAddtime());
                            } else {
                                eva_ll.setVisibility(View.GONE);
                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 添加收藏
    private void httpGetaccessories_goods_collection() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getaccessories_goods_collection, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            JSONObject js = new JSONObject(Response);
                            String type = js.getString("type");
                            if (type.equals("1")) {
                                Drawable img = getResources().getDrawable(R.mipmap.pic37_1);
                                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
                                part_addcoll.setCompoundDrawables(null, img, null, null);
                            } else if (type.equals("2")) {
                                Drawable img = getResources().getDrawable(R.mipmap.pic37_2);
                                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
                                part_addcoll.setCompoundDrawables(null, img, null, null);
                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 加入购物车
    private void httpGetadd_user_cart(String specid, String count) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("specifications_id", specid));
        list.add(new NameValuePairSign("count", count));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("specifications_id", specid);
        params.addQueryStringParameter("count", count);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getadd_user_cart, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetAppshare() {
        int rnd = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", rnd + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", rnd + "");
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.GetAppshare, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String jsonString = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            share(js.getString("img"), js.getString("title"), js.getString("content"), js.getString("url"));
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void share(final String img_url, final String title, final String context, final String link_url) {
        Dialog dlg = DialogUtil.ShowShareDialog(this, new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                UMImage img = new UMImage(PartsDetailActivity.this, img_url);
                switch (which) {
                    case R.id.share_friends:// 朋友圈
                        new ShareAction(PartsDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url).withMedia(img)
                                .share();
                        break;
                    case R.id.share_wxfriends:// 微信好友
                        new ShareAction(PartsDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url).withMedia(img)
                                .share();
                        break;
                    case R.id.share_sina:// 新浪
                        new ShareAction(PartsDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.SINA)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url)
                                // .withMedia(img)
                                .share();
                        break;
                    case R.id.share_QQfriends:// QQ好友
                        new ShareAction(PartsDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.QQ)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url)
                                //                                .withMedia(img)
                                .share();
                        break;
                }
                super.deal(which, obj);
            }
        });
        dlg.setCanceledOnTouchOutside(true);
        dlg.show();

        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
        params.width = width;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.getWindow().setAttributes(params);
    }

    /**
     * 轮播图点击事件
     */
    ImageCycleView.ImageCycleViewListener listener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void displayImage(Img img, ImageView imageView) {
            ImageLoader.getInstance().displayImage(img.getImg_url(), imageView);
        }

        @Override
        public void onImageClick(int position, View imageView) {
            Intent intent = new Intent();
            intent.setClass(PartsDetailActivity.this, ShowPictureActivity.class);
            intent.putExtra("image_uri", model.getImg_list().get(position).getImg_url());
            startActivity(intent);


        }

        @Override
        public void onImageChange(int position, List<Img> imageUrlList) {
        }
    };

    /**
     * 友盟分享回调
     */
    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.showToast("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showToast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            //            ToastUtils.showToast("分享取消了");
        }
    };

    //添加onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
